from mysqldb.header import *
from .serializers import *
from django.http import HttpResponse
from django.views import View

from . import tasks as TASKS

import logging

logger = logging.getLogger(__name__)

# pip install djangorestframework-xml


class MessageCallback(View):
    def get(self, request):
        signature = request.GET.get("signature")
        echostr = request.GET.get("echostr")
        timestamp = request.GET.get("timestamp")
        nonce = request.GET.get("nonce")
        token = "253100"
        # logger.info(f'GET: {signature} {token} {timestamp} {nonce}')

        list = [token, timestamp, nonce]
        list.sort()
        x = "".join(list)
        hashcode = hashlib.sha1(x.encode("utf8")).hexdigest()
        logger.debug(f"GET: {signature} {hashcode}")

        if hashcode == signature:
            return HttpResponse(echostr)
        else:
            return HttpResponse("err")

    def post(self, request):
        # logger.info(f'POST: {request.POST} {request.body}')
        body = request.body.decode("utf-8")
        # logger.info(f'POST: {body}')
        # r = TASKS.DoCheckWeChatEvent(body)
        r = TASKS.DoCheckWeChatEvent.apply_async((body,))
        return HttpResponse("success")


class WeChatMessageCallbackViewSet(viewsets.ModelViewSet):
    __title__ = "微信公众号消息回调(停用)"
    __group__ = "微信模块"
    __info__ = {"get": "接收微信公众号回调", "post": "接收微信公众号回调"}
    __doc__ = """	list:
    <h4>接收微信公众号回调</h4>
    retrieve:
    <h4>接收微信公众号回调</h4>
    create:
    <h4>接收微信公众号回调</h4>
    """
    http_method_names = ["get", "post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = NoneSerializer
    queryset = None

    # parser_classes = [rest_framework_xml.parsers.XMLParser]
    # renderer_classes = [rest_framework_xml.renderers.XMLRenderer]

    def list(self, request, *args, **kwargs):
        signature = request.query_params.get("signature")
        echostr = request.query_params.get("echostr")
        timestamp = request.query_params.get("timestamp")
        nonce = request.query_params.get("nonce")
        token = "253100"
        # logger.info(f'GET: {signature} {token} {timestamp} {nonce}')

        list = [token, timestamp, nonce]
        list.sort()
        x = "".join(list)
        hashcode = hashlib.sha1(x.encode("utf8")).hexdigest()
        # logger.info(f'GET: {hashcode}')

        if hashcode == signature:
            return HttpResponse(echostr)
        else:
            return Response({"rescode": 200, "resmsg": "err"})

    def create(self, request, *args, **kwargs):
        # serializer = self.serializer_class(data=request.data)
        # serializer.is_valid(raise_exception=True)
        # serializer.save()
        logger.info(f"POST: {request} {request.data}")
        return Response({"rescode": 200, "resmsg": ""})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})
